<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px"
             class="center">
      <el-form-item label="体系名称" prop="indicatorSystem.indicatorSystem.systemName" :rules="rules">
        <el-input
          v-model="indicatorSystem.indicatorSystem.systemName"
          placeholder="请输入要新建的指标体系名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-button icon="el-icon-refresh" size="mini" @click="reset">重置</el-button>
      <el-button type="primary" icon="el-icon-plus" size="mini" v-hasPermi="['system:system:add']" @click="addSystem">新建</el-button>
    </el-form>

    <el-row :gutter="20">
      <!-- 左边表 -->
      <el-col :span="6">
        <el-tree
          :data="dataList"
          :props="defaultProps"
          @check-change="handleSelect"
          node-key="id"
          :expand-on-click-node="false"
          :highlight-current="true"
          default-expand-all
          show-checkbox
          ref="tree"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span style="flex: 1; margin-right: 8px;">{{ data.indicatorName }}</span>
          </span>
        </el-tree>
      </el-col>

      <el-col :span="18">
        <!-- 关键修改点：添加 tree-props 属性 -->
        <el-table
          v-loading="loading"
          :data="dataList2"
          row-key="id"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          lazy
          default-expand-all
        >
          <el-table-column label="指标名称" align="center" prop="indicatorName" :show-overflow-tooltip="true"/>
          <el-table-column label="指标介绍" align="center" prop="description" :show-overflow-tooltip="true"/>
          <el-table-column label="主观权重" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <div style="display: flex; align-items: center;">
                <el-input-number
                  v-model="weightMap[scope.row.id]"
                  v-if="!scope.row.children"
                :min="0"
                :max="1"
                :step="0.01"
                :precision="2"
                :controls="false"
                :controls-position="'right'"
                clearable
                style="width: 80px; height: 40px"
                @change="handleWeightChange(scope.row.id)"
                />
                <!-- 红色星号：当权重为空或不在 [0,1] 范围内时显示 -->
                <span
                  v-if="!scope.row.children && (!weightMap[scope.row.id] && weightMap[scope.row.id] !== 0 || weightMap[scope.row.id] < 0 || weightMap[scope.row.id] > 1)"
                  style="color: red; margin-left: 4px;"
                >*</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getIndicatorsTree } from "@/api/indicator/indicator";
import { addSystem } from "@/api/indicator/system";

export default {
  name: "newIndex",
  data() {
    return {
      loading: true,
      showSearch: true,
      queryParams: {},
      indicatorSystem: {
        indicatorSystem: { systemName: '' },
        indicatorWeight: []
      },
      rules: {
        systemName: [
          { required: true, message: '体系名称不可为空！', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ]
      },
      dataList: [],
      dataList2: [],
      weightMap: {}, // 改为普通对象，支持响应式
      defaultProps: {
        children: "children",
        label: "indicatorName",
        isLeaf: "!children"
      },
      allSelectedNodes: new Set()
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 权重变更时校验
    handleWeightChange(id) {
      const val = this.weightMap[id];
      if (val === null || val === undefined || val === '') {
        this.$delete(this.weightMap, id); // 清除无效值
        return;
      }
      if (val < 0 || val > 1) {
        this.$message.warning('权重必须在 0 到 1 之间');
        // 可选：自动修正为边界值
        // this.weightMap[id] = val < 0 ? 0 : 1;
      }
    },

    // 全局校验所有选中节点的权重
    validateAllWeights() {
      // 递归获取所有叶子节点 ID
      const getLeafNodes = (nodes, leafIds = []) => {
        nodes.forEach(node => {
          if (!node.children || node.children.length === 0) {
            leafIds.push(node.id);
          } else {
            getLeafNodes(node.children, leafIds);
          }
        });
        return leafIds;
      };

      const leafNodeIds = getLeafNodes(this.dataList2); // 基于过滤后的数据验证叶子节点

      for (let id of leafNodeIds) {
        const weight = this.weightMap[id];
        if (weight === undefined || weight === null || weight === '') {
          // 尝试找到节点名称
          const findNodeName = (nodes, targetId) => {
            for (let node of nodes) {
              if (node.id === targetId) return node.indicatorName;
              if (node.children) {
                const found = findNodeName(node.children, targetId);
                if (found) return found;
              }
            }
            return '未知节点';
          };
          const nodeName = findNodeName(this.dataList2, id);
          this.$message.error(`指标 "${nodeName}" 的权重不能为空`);
          return false;
        }
        if (weight < 0 || weight > 1) {
          const findNodeName = (nodes, targetId) => {
            for (let node of nodes) {
              if (node.id === targetId) return node.indicatorName;
              if (node.children) {
                const found = findNodeName(node.children, targetId);
                if (found) return found;
              }
            }
            return '未知节点';
          };
          const nodeName = findNodeName(this.dataList2, id);
          this.$message.error(`指标 "${nodeName}" (${id}) 的权重必须在 0 到 1 之间`);
          return false;
        }
      }
      return true;
    },


    addSystem() {
      if (!this.indicatorSystem.indicatorSystem.systemName) {
        this.$modal.msgError("体系名称不可以为空！");
        return;
      }

      // 先获取最新选中节点
      this.getSelectedNodes();

      // 校验权重
      if (!this.validateAllWeights()) {
        return;
      }

      this.$confirm('是否确认添加指标体系？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.indicatorSystem.indicatorWeight = [];
        // 遍历所有选中的叶子节点来构建权重列表
        const getLeafNodeIds = (nodes, ids = []) => {
          nodes.forEach(node => {
            if (!node.children || node.children.length === 0) {
              ids.push(node.id);
            } else {
              getLeafNodeIds(node.children, ids);
            }
          });
          return ids;
        };
        const leafIds = getLeafNodeIds(this.dataList2);

        for (let id of leafIds) { // 只处理叶子节点
          this.indicatorSystem.indicatorWeight.push({
            id: id,
            subjectiveWeight: this.weightMap[id]
          });
        }

        addSystem(this.indicatorSystem).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.$router.push({ path: '/access/system/index' });
        }).catch(() => {
          this.$modal.msgError("添加失败！");
        });
      });
    },

    // 修改 filterTree 函数以保留层级结构
    filterTree(treeNodes, idsToKeep) {
      function traverseAndFilter(nodes) {
        let filteredNodes = [];
        for (let node of nodes) {
          let newNode = null;
          // 检查当前节点是否被选中
          if (idsToKeep.has(node.id)) {
            // 如果当前节点被选中，直接复制
            newNode = { ...node };
          } else if (node.children && node.children.length > 0) {
            // 如果当前节点未被选中，但其子节点可能被选中，则递归过滤子节点
            const filteredChildren = traverseAndFilter(node.children);
            if (filteredChildren.length > 0) {
              // 如果子节点中有被选中的，创建新节点并包含过滤后的子节点
              newNode = { ...node, children: filteredChildren };
            }
          }
          // 只有当节点或其子节点被选中时，才添加到结果中
          if (newNode) {
            // 确保 children 属性存在，即使为空数组，以便 el-table 识别为父节点
            if (!newNode.children) {
              newNode.children = [];
            }
            filteredNodes.push(newNode);
          }
        }
        return filteredNodes;
      }
      return traverseAndFilter(treeNodes);
    },

    getSelectedNodes() {
      const checked = this.$refs.tree.getCheckedKeys();
      const halfChecked = this.$refs.tree.getHalfCheckedKeys();
      this.allSelectedNodes = new Set([...checked, ...halfChecked]);
      this.dataList2 = this.filterTree(this.dataList, this.allSelectedNodes);
    },

    reset() {
      this.indicatorSystem.indicatorSystem.systemName = '';
      this.weightMap = {}; // 重置为新对象
      this.getList();
    },

    handleSelect() {
      this.getSelectedNodes();
    },

    getList() {
      this.loading = true;
      getIndicatorsTree(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.loading = false;
      });
    },

    handleQuery() {
      this.getList();
    }
  }
};
</script>

<style scoped>
.center {
  text-align: center;
}
</style>
